<script setup>
import axios from 'axios'
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Plus } from '@element-plus/icons-vue'
import { artPublishService, artGetDetailService, artEditService } from '@/api/article'
import { baseURL } from '@/utils/request'
import { ElMessage } from 'element-plus'
const loading = ref(false)
const emit = defineEmits(['success'])
const visibleDrawer = ref(false)
const defaultForm = ref({
    title: '',
    cate_id: '',
    content: '',
    cover_img: '',
    state: ''
})
const formModel = ref({
    title: '',
    cate_id: '',
    cover_img: '',
    content: '',
    state: ''
})
const imageUrl = ref('')

// 将网络图片地址转换为File对象

async function imageUrlToFile(url, fileName) {
    try {
        // 第一步：使用axios获取网络图片数据
        const response = await axios.get(url, { responseType: 'arraybuffer' })
        const imageData = response.data
        // 第二步：将图片数据转换为Blob对象
        const blob = new Blob([imageData], { type: response.headers['content-type'] })
        // 第三步：创建一个新的File对象
        const file = new File([blob], fileName, { type: blob.type })
        return file
    } catch (error) {
        console.error('将图片转换为File对象时发生错误:', error)

        throw error
    }
}
const open = async row => {
    loading.value = true
    visibleDrawer.value = true
    imageUrl.value = ''
    if (row.id) {
        const res = await artGetDetailService(row.id)
        formModel.value = res.data.data
        imageUrl.value = baseURL + formModel.value.cover_img
        // 网络图片转成 file 对象, 需要转换一下
        formModel.value.cover_img = await imageUrlToFile(imageUrl.value, formModel.value.cover_img)
    } else {
        imageUrl.value = ''
        editorRef.value.setHTML('')
        formModel.value = { ...defaultForm }
    }
    loading.value = false
}
defineExpose({
    open
})
const editorRef = ref()
const onSelectFile = uploadFile => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
    formModel.value.cover_img = uploadFile.raw
}

const onPublish = async state => {
    formModel.value.state = state
    const fd = new FormData()
    for (let k in formModel.value) {
        fd.append(k, formModel.value[k])
    }
    //编辑
    if (formModel.value.id) {
        await artEditService(fd)
        ElMessage.success('编辑成功')
    } else {
        await artPublishService(fd)
        ElMessage.success('添加成功')
    }
    visibleDrawer.value = false
    emit('success', 'add')
}
</script>

<template>
    <el-drawer v-model="visibleDrawer" :title="formModel.id ? '编辑文章' : '添加文章'" direction="rtl" size="50%">
        <!-- 发表文章表单 -->

        <el-form :model="formModel" ref="formRef" label-width="100px" v-loading="loading">
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
            </el-form-item>

            <el-form-item label="文章分类" prop="cate_id">
                <channel-select v-model="formModel.cate_id" width="100%"></channel-select>
            </el-form-item>

            <el-form-item label="文章封面" prop="cover_img">
                <el-upload :auto-upload="false" class="avatar-uploader" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :show-file-list="false" :on-change="onSelectFile">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="文章内容" prop="content">
                <div class="editor">
                    <QuillEditor ref="editorRef" theme="snow" v-model:content="formModel.content" content-type="html" />
                </div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
                <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
.editor {
    width: 100%;
    .ql-editor {
        min-height: 400px;
    }
}
</style>
